#!/usr/bin/env python3
"""
文档分析统计工具
提供字符、词汇、语句和代码结构的统计分析功能
"""

import sys
import re
import os
from pathlib import Path


class DocumentAnalyzer:
    """文档分析器核心类"""
    
    def __init__(self, file_path):
        self.file_path = Path(file_path)
        self.text_content = ""
        self._load_document()
    
    def _load_document(self):
        """加载文档内容，自动处理编码问题"""
        if not self.file_path.exists():
            raise FileNotFoundError(f"文档 '{self.file_path}' 不存在")
        
        # 支持的编码列表
        encodings_to_try = ['utf-8', 'gbk', 'gb2312', 'latin-1', 'iso-8859-1']
        
        for encoding in encodings_to_try:
            try:
                with open(self.file_path, 'r', encoding=encoding) as file:
                    self.text_content = file.read()
                return
            except UnicodeDecodeError:
                continue
        
        # 如果所有编码都失败，使用二进制模式读取
        try:
            with open(self.file_path, 'rb') as file:
                binary_data = file.read()
                self.text_content = binary_data.decode('utf-8', errors='replace')
        except Exception as e:
            raise IOError(f"无法读取文档: {e}")
    
    def get_character_count(self):
        """计算文档总字符数"""
        return len(self.text_content)
    
    def get_word_count(self):
        """计算文档词汇数量"""
        # 使用正则表达式分割单词，处理多种空白字符
        words = re.findall(r'\b\w+\b', self.text_content)
        return len(words)
    
    def get_sentence_count(self):
        """计算文档语句数量"""
        # 使用句子结束标点进行分割
        sentences = re.split(r'[.!?。！？]+', self.text_content)
        # 过滤空语句
        valid_sentences = [s.strip() for s in sentences if s.strip()]
        return len(valid_sentences)
    
    def analyze_document_structure(self):
        """分析文档结构：行数统计"""
        lines = self.text_content.split('\n')
        total_count = len(lines)
        blank_count = 0
        note_count = 0
        content_count = 0
        
        # 判断是否为代码文件
        file_suffix = self.file_path.suffix.lower()
        code_file_types = {'.py', '.java', '.c', '.cpp', '.js', '.html', '.css', '.php', '.rb'}
        is_code_document = file_suffix in code_file_types
        
        for current_line in lines:
            clean_line = current_line.strip()
            
            # 统计空白行
            if not clean_line:
                blank_count += 1
                continue
            
            # 代码文件的注释分析
            if is_code_document:
                if clean_line.startswith('#'):
                    note_count += 1
                elif '#' in clean_line:
                    # 处理行内注释
                    main_content = clean_line.split('#')[0].strip()
                    if main_content:
                        content_count += 1
                        note_count += 1
                    else:
                        note_count += 1
                else:
                    content_count += 1
            else:
                # 普通文档的所有非空行都视为内容行
                content_count += 1
        
        return {
            'total': total_count,
            'blank': blank_count,
            'notes': note_count,
            'content': content_count
        }


def display_help():
    """显示使用帮助信息"""
    help_text = """
文档分析统计工具

使用方法:
    python doc_analyzer.py [选项] [文件路径]

可用选项:
    -c  统计字符数量
    -w  统计词汇数量  
    -s  统计语句数量
    -l  分析文档结构（行数统计）

示例:
    python doc_analyzer.py -c example.txt
    python doc_analyzer.py -l script.py
    """
    print(help_text)


def execute_analysis():
    """执行文档分析任务"""
    if len(sys.argv) != 3:
        display_help()
        sys.exit(1)
    
    option_flag = sys.argv[1]
    target_file = sys.argv[2]
    
    # 验证文件是否存在
    if not os.path.isfile(target_file):
        print(f"错误：目标文件 '{target_file}' 未找到")
        sys.exit(1)
    
    try:
        analyzer = DocumentAnalyzer(target_file)
        
        if option_flag == '-c':
            result = analyzer.get_character_count()
            print(f"文档字符总数: {result}")
            
        elif option_flag == '-w':
            result = analyzer.get_word_count()
            print(f"文档词汇总数: {result}")
            
        elif option_flag == '-s':
            result = analyzer.get_sentence_count()
            print(f"文档语句总数: {result}")
            
        elif option_flag == '-l':
            structure_info = analyzer.analyze_document_structure()
            print("=== 文档结构分析 ===")
            print(f"总行数:    {structure_info['total']}")
            print(f"空白行:    {structure_info['blank']}")
            print(f"注释行:    {structure_info['notes']}")
            print(f"内容行:    {structure_info['content']}")
            
        else:
            print("错误：无效的参数选项")
            display_help()
            sys.exit(1)
            
    except Exception as error:
        print(f"分析过程中出现错误: {error}")
        sys.exit(1)


if __name__ == '__main__':
    execute_analysis()